import { validatenull } from './validate';
import _ from 'lodash-es';
//表单序列化
export const serialize = (data) => {
  let list = [];
  Object.keys(data).forEach((ele) => {
    list.push(`${ele}=${data[ele]}`);
  });
  return list.join('&');
};
export const getObjType = (obj) => {
  var toString = Object.prototype.toString;
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  };
  if (obj instanceof Element) {
    return 'element';
  }
  return map[toString.call(obj)];
};
export const getViewDom = () => {
  return window.document.getElementById('avue-view').getElementsByClassName('el-scrollbar__wrap')[0];
};
/**
 * 对象深拷贝
 */
export const deepClone = (data) => {
  var type = getObjType(data);
  var obj;
  if (type === 'array') {
    obj = [];
  } else if (type === 'object') {
    obj = {};
  } else {
    //不再具有下一层次
    return data;
  }
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]));
    }
  } else if (type === 'object') {
    for (var key in data) {
      obj[key] = deepClone(data[key]);
    }
  }
  return obj;
};
/**
 * 设置灰度模式
 */
export const toggleGrayMode = (status) => {
  if (status) {
    document.body.className = document.body.className + ' grayMode';
  } else {
    document.body.className = document.body.className.replace(' grayMode', '');
  }
};
/**
 * 设置主题
 */
export const setTheme = (name) => {
  document.body.className = name;
};

/**
 * 加密处理
 */
export const encryption = (params) => {
  let { data, type, param, key } = params;
  let result = JSON.parse(JSON.stringify(data));
  if (type == 'Base64') {
    param.forEach((ele) => {
      result[ele] = btoa(result[ele]);
    });
  } else if (type == 'Aes') {
    param.forEach((ele) => {
      result[ele] = window.CryptoJS.AES.encrypt(result[ele], key).toString();
    });
  }
  return result;
};

/**
 * 浏览器判断是否全屏
 */
export const fullscreenToggel = () => {
  if (fullscreenEnable()) {
    exitFullScreen();
  } else {
    reqFullScreen();
  }
};
/**
 * esc监听全屏
 */
export const listenfullscreen = (callback) => {
  function listen() {
    callback();
  }

  document.addEventListener('fullscreenchange', function () {
    listen();
  });
  document.addEventListener('mozfullscreenchange', function () {
    listen();
  });
  document.addEventListener('webkitfullscreenchange', function () {
    listen();
  });
  document.addEventListener('msfullscreenchange', function () {
    listen();
  });
};
/**
 * 浏览器判断是否全屏
 */
export const fullscreenEnable = () => {
  var isFullscreen = document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen;
  return isFullscreen;
};

/**
 * 浏览器全屏
 */
export const reqFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.documentElement.requestFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.documentElement.webkitRequestFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.documentElement.mozRequestFullScreen();
  }
};
/**
 * 浏览器退出全屏
 */
export const exitFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.exitFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.webkitCancelFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.mozCancelFullScreen();
  }
};
/**
 * 递归寻找子类的父类
 */

export const findParent = (menu, id) => {
  for (let i = 0; i < menu.length; i++) {
    if (menu[i].children.length != 0) {
      for (let j = 0; j < menu[i].children.length; j++) {
        if (menu[i].children[j].id == id) {
          return menu[i];
        } else {
          if (menu[i].children[j].children.length != 0) {
            return findParent(menu[i].children[j].children, id);
          }
        }
      }
    }
  }
};
/**
 * 判断2个对象属性和值是否相等
 */

/**
 * 动态插入css
 */

export const loadStyle = (url) => {
  const link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.href = url;
  const head = document.getElementsByTagName('head')[0];
  head.appendChild(link);
};
/**
 * 判断路由是否相等
 */
export const diff = (obj1, obj2) => {
  delete obj1.close;
  var o1 = obj1 instanceof Object;
  var o2 = obj2 instanceof Object;
  if (!o1 || !o2) {
    /*  判断不是对象  */
    return obj1 === obj2;
  }

  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
    //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
  }

  for (var attr in obj1) {
    var t1 = obj1[attr] instanceof Object;
    var t2 = obj2[attr] instanceof Object;
    if (t1 && t2) {
      return diff(obj1[attr], obj2[attr]);
    } else if (obj1[attr] !== obj2[attr]) {
      return false;
    }
  }
  return true;
};
/**
 * 根据字典的value显示label
 */
export const findByvalue = (dic, value) => {
  let result = '';
  if (validatenull(dic)) return value;
  if (typeof value == 'string' || typeof value == 'number' || typeof value == 'boolean') {
    let index = 0;
    index = findArray(dic, value);
    if (index != -1) {
      result = dic[index].label;
    } else {
      result = value;
    }
  } else if (value instanceof Array) {
    result = [];
    let index = 0;
    value.forEach((ele) => {
      index = findArray(dic, ele);
      if (index != -1) {
        result.push(dic[index].label);
      } else {
        result.push(value);
      }
    });
    result = result.toString();
  }
  return result;
};
/**
 * 根据字典的value查找对应的index
 */
export const findArray = (dic, value) => {
  for (let i = 0; i < dic.length; i++) {
    if (dic[i].value == value) {
      return i;
    }
  }
  return -1;
};
/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
  let random = '';
  random = Math.ceil(Math.random() * 100000000000000)
    .toString()
    .substr(0, len ? len : 4);
  if (date) random = random + Date.now();
  return random;
};
/**
 * 打开小窗口
 */
export const openWindow = (url, title, w, h) => {
  // Fixes dual-screen position                            Most browsers       Firefox
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
  const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;

  const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
  const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

  const left = width / 2 - w / 2 + dualScreenLeft;
  const top = height / 2 - h / 2 + dualScreenTop;
  const newWindow = window.open(
    url,
    title,
    'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' +
      w +
      ', height=' +
      h +
      ', top=' +
      top +
      ', left=' +
      left
  );

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus();
  }
};

/**
 * 获取顶部地址栏地址
 */
export const getTopUrl = () => {
  return window.location.href.split('/#/')[0];
};

/**
 * 获取url参数
 * @param name 参数名
 */
export const getQueryString = (name) => {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  let r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(decodeURI(r[2]));
  return null;
};

export const downloadFileByUrl = (url, name) => {
  const a = document.createElement('a'); //创建a标签
  a.style.display = 'none';
  a.href = url; // 指定下载链接
  a.download = name; //指定下载文件名
  document.body.appendChild(a);
  a.click(); //触发下载
  //在资源下载完成后 清除 占用的缓存资源
  window.URL.revokeObjectURL(a.href);
  document.body.removeChild(a);
};

export const downloadExcel = (data, name) => {
  const blob = new Blob([data], { type: 'application/vnd.ms-excel;charset=UTF-8' }); // 构造一个blob对象来处理数据，并设置文件类型
  if (window.navigator.msSaveOrOpenBlob) {
    //兼容IE10
    navigator.msSaveBlob(blob, name);
  } else {
    const href = URL.createObjectURL(blob); //创建新的URL表示指定的blob对象
    const a = document.createElement('a'); //创建a标签
    a.style.display = 'none';
    a.href = href; // 指定下载链接
    a.download = name; //指定下载文件名
    a.click(); //触发下载
    URL.revokeObjectURL(a.href); //释放URL对象
  }
};
/**
 * 下载文件
 * @param {String} path - 文件地址
 * @param {String} name - 文件名,eg: test.png
 */
export const downloadFileBlob = (path, name) => {
  const xhr = new XMLHttpRequest();
  xhr.open('get', path);
  xhr.responseType = 'blob';
  xhr.send();
  xhr.onload = function () {
    if (this.status === 200 || this.status === 304) {
      // 如果是IE10及以上，不支持download属性，采用msSaveOrOpenBlob方法，但是IE10以下也不支持msSaveOrOpenBlob
      if ('msSaveOrOpenBlob' in navigator) {
        navigator.msSaveOrOpenBlob(this.response, name);
        return;
      }
      const url = URL.createObjectURL(this.response);
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = name;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  };
};

/**
 * 下载文件
 * @param {String} path - 文件地址
 * @param {String} name - 文件名,eg: test.png
 */
export const downloadFileBase64 = (path, name) => {
  const xhr = new XMLHttpRequest();
  xhr.open('get', path);
  xhr.responseType = 'blob';
  xhr.send();
  xhr.onload = function () {
    if (this.status === 200 || this.status === 304) {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(this.response);
      fileReader.onload = function () {
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = this.result;
        a.download = name;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      };
    }
  };
};

export const getIlistId = (values) => {
  let arr = [];
  if (values && Object.prototype.toString.call(values) == '[object Array]') {
    arr = values.map(({ id }) => {
      return { id };
    });
    return arr;
  } else {
    [];
  }
};

export const cutSameItem = (arr) => {
  let result = [];
  let obj = {};
  for (var i = 0; i < arr.length; i++) {
    if (!obj[arr[i].key]) {
      result.push(arr[i]);
      obj[arr[i].key] = true;
    }
  }
  return result;
};

/**
 * 计算时间差值
 * @param {开始时间} startTime
 * @param {结束时间} endTime
 * @returns
 */
export const timeDifference = (startTime, endTime) => {
  //可以传日期时间或时间戳
  let start = typeof startTime == 'number' ? startTime : new Date(startTime).getTime(),
    end = typeof endTime == 'number' ? endTime : new Date(endTime).getTime(),
    difference = end - start, //时间差的毫秒数
    days = Math.floor(difference / (24 * 3600 * 1000)), //计算出相差天数
    leave1 = difference % (24 * 3600 * 1000), //计算天数后剩余的毫秒数
    hours = Math.floor(leave1 / (3600 * 1000)), //计算相差分钟数
    leave2 = leave1 % (3600 * 1000), //计算小时数后剩余的毫秒数
    minutes = Math.floor(leave2 / (60 * 1000)), //计算相差秒数
    leave3 = leave2 % (60 * 1000), //计算分钟数后剩余的毫秒数
    seconds = Math.round(leave3 / 1000);
  if (days) {
    return `${days}天${hours}小时${minutes}分钟`;
  } else if (hours) {
    return `${hours}小时${minutes}分钟`;
  } else {
    return `${minutes}分钟`;
  }
};

export const compareTime = (time1, time2) => {
  let oDate1 = new Date(time1);
  let oDate2 = new Date(time2);
  if (oDate1.getTime() > oDate2.getTime()) {
    return 1;
  } else if (oDate1.getTime() == oDate2.getTime()) {
    return 0;
  } else {
    return 2;
  }
};
// assignName:显示指定名字
export const structuralSplit = (assignName) => {
  console.log($('.informationLabel'));
  if ($('.informationLabel').length === 0) {
    let saberTag = localStorage.getItem('saber-tag');
    let tagLabel = JSON.parse(saberTag).content.label;
    let card = $('#app .el-card .is-never-shadow');
    console.log(card);
    let searchSon = $(card[0]).find('.avue-form');
    let searchFather = document.createElement('div');
    searchFather.className = 'informationLabel el-tabs el-tabs--top el-tabs--border-card';
    searchFather.innerHTML = `<div class="el-tabs__header is-top">
              <div class="el-tabs__content" style="padding: 10px 10px 0 10px;background-color: #ffffff;"></div>
            </div>`;
    $(searchFather).find('.el-tabs__content').append(searchSon);
    $('#app .avue-crud__search .el-card__body').append(searchFather);

    let tableSon = $(card[1]).find('.el-card__body');
    let tableFather = document.createElement('div');
    tableFather.className = 'informationLabel el-tabs el-tabs--top el-tabs--border-card';
    tableFather.innerHTML = `<div class="el-tabs__header is-top">
              <div class="el-tabs__content" style="padding: 10px 10px 0 10px;background-color: #ffffff;"></div>
            </div>`;
    $(tableFather).find('.el-tabs__content').append(tableSon);
    console.log(tableFather);
    $(card[1]).append(tableFather);
    let elCardBody = $('.basic-container__card').find('.el-card__body');
    $(elCardBody[0]).addClass('el-card__body__padding');
  }
};
// 下划线转驼峰
export function underlineToCamel(str) {
  return str.replace(/_([a-z])/g, function (match, p1) {
    return p1.toUpperCase();
  });
}
//驼峰转下划线
export function camelToUnderline(str) {
  return str.replace(/[A-Z]/g, function (match) {
    return '_' + match.toLowerCase();
  });
}

export function handleJumpCache(vm, next, from, path) {
  next((vm) => {
    if (from && from.path.startsWith(path) && from.name == '工单管理') {
      // Object.keys(vm.search).forEach((key) => {
      //     vm.search[key] = '';
      // });
      vm.page.currentPage = 1;
      vm.refreshChange();
    }
    if (from && from.name == '设计产品工艺路线') {
      vm.page.currentPage = 1;
      vm.refreshChange();
    }
  });
}
// 过滤对象空值
export function filterEmptyValues(obj) {
  const cloneObj = _.cloneDeep(obj);
  for (let key in cloneObj) {
    if (cloneObj[key] === null || cloneObj[key] === undefined || cloneObj[key] === '') {
      delete cloneObj[key];
    }
  }
  return cloneObj;
}

/**
 * 数组去重
 * @param {*} data
 * @returns
 */
export const filterArray = (data) => {
  return [...new Set(data)];
};

export const dragDialog = (self) => {
  const dialogHeaderEl = self.$el.querySelector('.el-dialog__header');
  const dragDom = self.$el.querySelector('.el-dialog');
  dialogHeaderEl.style.cssText += ';cursor:move;';
  dragDom.style.cssText += ';top:0px;';
  // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
  const sty = (() => {
    if (window.document.currentStyle) {
      return (dom, attr) => dom.currentStyle[attr];
    } else {
      return (dom, attr) => getComputedStyle(dom, false)[attr];
    }
  })();

  dialogHeaderEl.onmousedown = (e) => {
    // 鼠标按下，计算当前元素距离可视区的距离
    const disX = e.clientX - dialogHeaderEl.offsetLeft;
    const disY = e.clientY - dialogHeaderEl.offsetTop;

    const screenWidth = document.body.clientWidth; // body当前宽度
    const screenHeight = document.documentElement.clientHeight; // 可见区域高度(应为body高度，可某些环境下无法获取)

    const dragDomWidth = dragDom.offsetWidth; // 对话框宽度
    const dragDomheight = dragDom.offsetHeight; // 对话框高度

    const minDragDomLeft = dragDom.offsetLeft;
    const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth;

    const minDragDomTop = dragDom.offsetTop;
    const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomheight;

    // 获取到的值带px 正则匹配替换
    let styL = sty(dragDom, 'left');
    let styT = sty(dragDom, 'top');

    // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
    if (styL.includes('%')) {
      styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100);
      styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100);
    } else {
      styL = +styL.replace(/\px/g, '');
      styT = +styT.replace(/\px/g, '');
    }

    document.onmousemove = function (e) {
      // 通过事件委托，计算移动的距离
      let left = e.clientX - disX;
      let top = e.clientY - disY;

      // 边界处理
      if (-left > minDragDomLeft) {
        left = -minDragDomLeft;
      } else if (left > maxDragDomLeft) {
        left = maxDragDomLeft;
      }

      if (-top > minDragDomTop) {
        top = -minDragDomTop;
      } else if (top > maxDragDomTop) {
        top = maxDragDomTop;
      }

      // 移动当前元素
      dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`;
    };

    document.onmouseup = function (e) {
      document.onmousemove = null;
      document.onmouseup = null;
    };
  };
};

export function traverseTree(data, callback, childrenKey = 'children') {
  // 树形结构遍历
  if (!data || !callback) {
    throw new Error('please check parameter:', data, callback);
  }
  data.forEach((item) => {
    callback(item);
    const children = item[childrenKey];
    if (children) {
      traverseTree(children, callback, childrenKey);
    }
  });
}

export const flatTreeToList = (data) => {
  let resList = [];
  function travelTree(tree, level) {
    tree.forEach((item) => {
      item._level = level;
      item._isExpand = false;
      item._isShow = true;
      resList.push(item);
      if (item.children && item.children.length) {
        // level = level + 1;
        travelTree(item.children, level + 1);
      }
    });
  }
  travelTree(data, 0);
  return resList;
};

export const flatTreeToListWithoutStatus = (data) => {
  let resList = [];
  function travelTree(tree, level) {
    tree.forEach((item) => {
      resList.push(item);
      if (item.children && item.children.length) {
        // level = level + 1;
        travelTree(item.children, level + 1);
      }
    });
  }
  travelTree(data, 0);
  return resList;
};
export function findAndAddChildren(tree, id, children) {
  console.log(tree);
  if (!Array.isArray(tree)) {
    return false;
  }
  for (const node of tree) {
    if (node.id === id) {
      if (!node.children) {
        node.children = [];
      }
      node.children = children;
      return true;
    }
    if (node.children && node.children.length > 0) {
      const found = findAndAddChildren(node.children, id, children);
      if (found) {
        return true;
      }
    }
  }
  return false;
}

export function findNodeById(tree, id) {
  if (!Array.isArray(tree)) {
    return null;
  }

  for (const node of tree) {
    if (node.id === id) {
      return node;
    }

    if (node.children && node.children.length > 0) {
      const foundNode = findNodeById(node.children, id);
      if (foundNode) {
        return foundNode;
      }
    }
  }

  return null;
}

export const stringToBoolean = (str) => {
  if (str === 'false') str = false;
  return Boolean(str);
};
